package Example;

import javax.imageio.stream.ImageInputStream;
import java.io.*;
import java.util.Scanner;

public class Demo02 {
    public static void main(String[] args) {
//        文件复制
//        将第一个文件用读方式打开, 依次读取文件中的每一个字节 然后写入另一个文件中

        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要复制的源文件");
        String srcPath = scanner.next();
        System.out.println("请输入要复制的目标文件");
        String destPath = scanner.next();
        scanner.close();

//        判断源文件是否存在
        File srcFile = new File(srcPath);
        if (!srcFile.isFile()){
            System.out.println("源文件路径有误! ");
            return;
        }

        // 创建目标文件对象
        File destFile = new File(destPath);
        if (!destFile.getParentFile().isDirectory()){
            System.out.println("目标路径有误! ");
            return;
        }

        // 执行文件复制操作
        try(InputStream inputStream = new FileInputStream(srcFile);
            OutputStream outputStream = new FileOutputStream(destFile)){
            byte[] buffer = new byte[1024];
            int bytesRead;
            while((bytesRead = inputStream.read(buffer)) != -1){
                outputStream.write(buffer,0,bytesRead);
            }
            System.out.println("文件复制成功! ");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("文件复制失败! ");
        }
    }
}
